package MTT::Libs::Param::AlarmParam;

use Moose;

has schema => ( is => 'ro' );

has id => ( is => 'ro', writer => 'set_id' );
has name => ( is => 'ro', writer => 'set_name' );
has descr => ( is => 'ro', writer => 'set_descr' );
has compute => ( is => 'ro', writer => 'set_compute' );

has alarm_id => ( is => 'rw' );
has condition => ( is => 'rw' );


sub BUILD {
	my ($self, $args) = @_;

	if ( my $item = $args->{item} ) {
		if ( ref($item) =~ /AlarmParam$/ ) {
			$self->set_id( $item->id_param->id );
			$self->set_name( $item->id_param->name );
			$self->set_descr( $item->id_param->descr );
			$self->set_compute( $item->id_param->compute );
			$self->alarm_id( $item->id_alarm->id );
			$self->condition( $item->cond );
		}
		elsif ( ref($item) =~ /\:\:Param$/ ) {
			$self->set_id( $item->id );
			$self->set_name( $item->name );
			$self->set_descr( $item->descr );
			$self->set_compute( $item->compute );
		}
	}
	elsif ( $self->schema ) {
		my $param;
		if ( $self->id ) {
			$param = $self->schema->resultset('Param')->find( $self->id );
			die "Param ${\( $self->id )} not found" unless $param;
		}
		elsif ( $self->name ) {
			$param = $self->schema->resultset('Param')->find( $self->name );
			die "Param ${\( $self->name )} not found" unless $param;
		}

		if ( $param ) {
			$self->set_name( $param->name );
			$self->set_descr( $param->descr );
			$self->set_compute( $param->compute );

			if ( $self->alarm_id ) {
				my $alarm_param = $self->schema->resultset('AlarmParam')->find({
						alarm_id => $self->alarm_id,
						param_id => $self->id
					});
				die "Alarm param ${(\ $self->id )} not found" unless $alarm_param;  

				$self->condition( $alarm_param->cond ) unless $self->condition;
			}
		}
	}

	return $self;
}

sub save {
	my ($self) = @_;
	
	die "Cannot save alarm parameter without param_id and alarm_id" unless $self->id && $self->alarm_id;

	my $alarm_param = $self->schema->resultset('AlarmParam')->find({
			alarm_id => $self->alarm_id,
			param_id => $self->id
		});

	if ( $alarm_param && $alarm_param->cond ne $self->condition ) {
		$alarm_param->update({ cond => $self->condition });
	}
}

__PACKAGE__->meta->make_immutable;
1;
